<!DOCTYPE html>
<html>
    <head>
        <title> 日期相关操作</title>
		<meta charset="utf-8" />
    </head>
    <body>

    </body>
    <script>
        //创建日期对象
        var date1 = new Date();

        //获取年份
        var year = date1.getFullYear();
        console.log(year);

        //获取的月份的取值范围是0-11
        var month = date1.getMonth();
        month = month + 1;
        console.log(month);

        //获取星期 日期对象.getDay()
        //获取星期的取值范围0-6
        //每个星期的第一天是星期日
        var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
        var weekday = date1.getDay();
        console.log(weeks[weekday]);

        //获取今天的日期 日起对象.getDate()
        var day = date1.getDate();
        console.log(day);

        //获取当前时刻
        var hour = date1.getHours();
        var minute = date1.getMinutes();
        var sec = date1.getSeconds();
        console.log(hour, minute, sec);

        /*
         * 创建函数，生成当前时间的字符串
         * 2021-10-19 10:17:20
         * 作为函数的返回值返回*/
        function identify(num){
            return num < 10 ? "0" + num : num;
        }
        function creatTimer(){
            var date1 = new Date();

            var m1 = date1.getMilliseconds();//毫秒
            var year = date1.getFullYear();
            var month = date1.getMonth() + 1;
            var day = date1.getDate();
            var hour = date1.getHours();
            var minute = date1.getMinutes();
            var sec = date1.getSeconds();

            month = identify(month);
            day = identify(day);
            hour = identify(hour);
            minute = identify(minute);
            sec = identify(sec);
            m1 = identify(m1);
            var result = year + "-" + month + "-" + day + " "+ hour + ":" + minute + ":"+ sec + ":" + m1;
            return result;
        }
        document.write(creatTimer() + "<br/>");

        document.write((new Date).toLocaleString());
    </script>
</html>